package backTrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Class90 {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<Integer>();
    boolean[]  flag;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        flag=new boolean[nums.length];
        Arrays.fill(flag,false);
        //  CKG TODO 2023/4/22:  涉及到去重 需要排序
        Arrays.sort(nums);
        backTracking(nums,flag,0);
        return  result;

    }

    public void backTracking(int[] nums, boolean[] flag,int start) {

        result.add(new ArrayList<>(path));
//        if (i>0&&nums[i]==nums[i-1]&&!flag[i-1]){
//            continue;
//        }

        if (start>=nums.length){
            return;
        }
        for (int i = start; i < nums.length ; i++) {
//  CKG TODO 2023/4/22: 去重在for循环中处理
            if (i>0&&nums[i]==nums[i-1]&&!flag[i-1]){
                continue;
            }
            flag[i]=true;
            path.add(nums[i] );
            backTracking(nums, flag,i+1);
            path.removeLast();
            flag[i]=false;
        }

    }

    public static void main(String[] args) {

        Class90 class90 = new Class90();
        int[] arr={4,4,4,1,4};
        System.out.println(class90.subsetsWithDup(arr).toString());
    }


}
